package com.example.finalapplication;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class PlantsTask  implements Runnable{
    private static final String TAG = "PlantsTask";
    private Handler handler;

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }


    @Override
    public void run() {
        try {
            Thread.sleep(2000);
  } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ArrayList<HashMap<String,String>> retList = new ArrayList<HashMap<String,String>>();


 try {
     for(int i=1;i<=21;i++) {
         String url = "http://db.kib.ac.cn/CNFlora/NameList.aspx?p=" + i;
         // Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
         Document doc = Jsoup.connect(url).get();
         String title = doc.title();
         Log.i(TAG, "run:title=" + title);

         Elements trs = doc.getElementsByTag("tr");
         for (Element tr : trs) {
             Elements tds = tr.getElementsByTag("td");
              Elements as = tr.getElementsByTag("a");
             Log.i(TAG, "run:td.size=" + tds.size());
             if (tds.size() > 0) {
                 String td1 = tds.get(0).text();
                 String td2 = tds.get(2).text();
                 String aHref=as.attr("href");
                 Log.i(TAG, "run:" + td2 + "==>" + td1 + "==>"+aHref);


                 //构造map放入数据
                 HashMap<String, String> map = new HashMap<String, String>();
                 map.put("cname", td2);
                 map.put("cval", td1);
                 map.put("href",aHref);
                 retList.add(map);
             }
         }
     }
        } catch (IOException e) {
            e.printStackTrace();
        }


        Message msg = handler.obtainMessage(6, retList);
        //msg.obj = "Hello";

        handler.sendMessage(msg);
        Log.i(TAG, "run:sendMessage ok");
    }
    }
